package eu.webmedia.recruitment.comics.strips;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.springframework.stereotype.Component;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

@Component
public class XkcdStripUrlFinder {
	
	public String findUrl() {
		String description;
		
		try {
			URL url = new URL("http://xkcd.com/rss.xml");
			InputStream stream = url.openStream();
			
			description = getDescription(stream);
			
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		
		Pattern descriptionPattern = Pattern.compile(".*src=\"(http://[^\"]*)\".*", Pattern.DOTALL);
		Matcher matcher = descriptionPattern.matcher(description);
		
		if (!matcher.matches()) {
			return null;
		}
		
		return matcher.group(1);
	}

	
	private String getDescription(InputStream stream) throws ParserConfigurationException, SAXException, IOException {
		DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
		Document doc = builder.parse(stream);
		
		NodeList nodes = doc.getElementsByTagName("item");
		
		Element firstItem = (Element) nodes.item(0);
		Element descriptionElement = (Element) firstItem.getElementsByTagName("description").item(0);
		
		return descriptionElement.getTextContent();
	}

}
